<template>
  <div class="cmt_container">
    <div class="comment">
      <h3 class="title">发表评论</h3>
      <textarea maxlength="120" placeholder="请开始你的表演(最多120字)"
        v-model="content">
      </textarea>
      
      <mt-button type="primary" size="large" 
        @click="addComment"
        @touchend.prevent="addComment">发表评论</mt-button>

      <div class="cmt-list">
        <div class="cmt-item" v-for="(item,i) in comments" :key="i">
          <div class="cmt-title">
            第{{ i+1 }}楼 用户：{{ item.user_name }} 发表时间：{{ item.add_time | dateFormat }}
          </div>
          <div class="cmt-content">
            {{ item.content === 'undefined'? '啥都没留下': item.content }}
          </div>
        </div>
      </div>
    </div>

    <mt-button type="danger" size="large" plain 
      @click="getMore"
      @touchend.prevent="getMore">加载更多</mt-button>
  </div>
</template>

<script>
import { Toast } from 'mint-ui'

export default {
  name: 'comment',
  data() {
    return {
      content: '',
      comments: [],
      pageNum: 1
    }
  },
  props: [ 'id' ],
  created() {
    this.getComment()
  },
  methods: {
    getComment() {
      this.$store.dispatch('getComments', { id: this.id, pageNum: this.pageNum }).then(res => {
        if(res.data.code === 200) {
          if(res.data.list == "") Toast('没有更多数据了')
          
          res.data.list.forEach(item => {
            if(/^\d+$/.test(item.add_time))
              item.add_time = Number(item.add_time)
          });
          this.comments = this.comments.concat(res.data.list)
        }
      })
    },
    addComment() {
      if(this.content.trim().length === 0)
        return Toast('留言不能为空')
      this.$store.dispatch('addComment', { id: this.id, content: this.content }).then(res => {
        if(res.data.code === 200){
          Toast('留言成功')
          const newCmt = {
            user_name: '匿名用户',
            add_time: new Date(),
            content: this.content.trim()
          }
          this.comments.unshift(newCmt)
          this.content = ''
        } else {
          Toast('发表留言失败')
        }
      })
    },
    getMore() {
      this.pageNum++
      this.getComment()
    }
  }
}
</script>

<style lang="less" scoped>
  .cmt_container {
    .comment {
      h3 {
        font-size: 18px;
        border-bottom: 2px solid #ddd;
        padding-bottom: 10px;
      }
      textarea {
        font-size: 14px;
        height: 85px;
        margin: 0;
      }
      .cmt-list {
        margin: 5px 0;

        .cmt-item {
          font-size: 13px;
          color: #000;
          .cmt-title {
            background-color: #ccc;
            line-height: 30px;
          }
          .cmt-content {
            line-height: 35px;
            text-indent: 2em;
          }
        }
      }
    }
  }
</style>
